<?php

namespace fakis\core\behaviors;

use fakis\core\base\Customizer;
use fakis\core\base\Serializer;
use Yii;
use yii\base\Request;
use yii\di\Instance;
use yii\helpers\ArrayHelper;
use yii\web\Response;

/**
 * Class ContentNegotiator
 *
 * @package core\behaviors
 * @author Fakis <fakis738@qq.com>
 */
class ContentNegotiator extends \yii\filters\ContentNegotiator
{
    /**
     * @var array
     */
    public $formats = [
        'text/html' => Response::FORMAT_HTML,
        'application/json' => Response::FORMAT_JSON,
        'application/xml' => Response::FORMAT_XML,
    ];

    public $enableResponseDataHandler = true;

    /**
     * {@inheritDoc}
     */
//    public function beforeAction($action)
//    {
//        print_r($action);exit;
//        if (parent::beforeAction($action)) {
//            $this->negotiateResponseSend();
//            return true;
//        }
//        return false;
//    }

    /**
     * {@inheritDoc}
     * @throws \yii\base\InvalidConfigException
     */
    public function afterAction($action, $result)
    {
        return $this->negotiateResponseData($result);
    }

    /**
     * 协商响应格式
     * @param mixed $result
     * @return mixed
     * @throws \yii\base\InvalidConfigException
     * @throws \Exception
     */
    protected function negotiateResponseData($result)
    {
        if ($this->enableResponseDataHandler !== true) {
            return $result;
        }

        $response = $this->response ?? Yii::$app->getResponse();

        // Response Content
        if (is_string($result) && in_array($response->format, [Response::FORMAT_RAW, Response::FORMAT_HTML], true)) {
            return $result;
        }

        // Response Data
        if (!in_array($response->format, $this->formats, true)) {
            $response->format = Response::FORMAT_JSON;
        }

        return $this->serializeData($result);
    }

    /**
     * 序列化数据
     * @param $result
     * @return mixed
     */
    protected function serializeData($result)
    {
        return (new Customizer())->serialize($result);
    }

    /**
     * 初始化响应格式
     */
//    protected function initFormats()
//    {
//        if (empty($this->formats)) {
//            $this->formats = [
//                'application/json' => Response::FORMAT_JSON,
//                'application/xml' => Response::FORMAT_XML,
//                'text/html' => Response::FORMAT_HTML,
//            ];
//        }
//    }
}